package config_table

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"path/filepath"
)

type (
	parser = func(records interface{}) (err error)
)

type configInfo struct {
	parser   parser
	item     interface{}
	filePath string
}

var (
	configs []*configInfo
)

func Init(configPath string) (err error) {
	if configPath == "" {
		return
	}

	read := func(item interface{}, filePath string) (err error) {
		filePath = filepath.Join(configPath, filePath)
		var data []byte
		if data, err = ioutil.ReadFile(filePath); err != nil {
			return
		}

		if err = json.Unmarshal(data, item); err != nil {
			return
		}

		return
	}

	for _, info := range configs {
		if err = read(info.item, info.filePath); err != nil {
			err = fmt.Errorf("read %s failed, %v", info.filePath, err)
			return
		}
	}

	for _, info := range configs {
		if err = info.parser(info.item); err != nil {
			return
		}
	}

	return
}

func register(parser parser, item interface{}, filePath string) {
	info := new(configInfo)
	info.parser = parser
	info.item = item
	info.filePath = filePath

	configs = append(configs, info)
}
